<template>
  <div class="form-container-wrap">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
          <el-button class="back-button" type="primary" @click="goBack">返回列表</el-button>
        </div>
      </template>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" class="form-content">
            <el-form-item label="姓名" prop="staffName">
          <el-input v-model="form.staffName" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
          <el-input v-model="form.role" placeholder="请输入角色（如兽医、美容师）" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">
            {{ isEdit ? '更新' : '新增' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { staffsApi } from '@/api'
import { Staffs } from '@/types'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance | null>(null)

const isEdit = ref(false)
const formTitle = ref('新增服务人员')

const form = reactive<Staffs>({
  staffId: undefined,
  staffName: '',
  role: ''
})

const rules: FormRules = {
  staffName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  role: [{ required: true, message: '请输入角色', trigger: 'blur' }]
}

onMounted(() => {
  console.log('路由参数:', route.params)
  const staffId = route.params.id || route.params.staffId
  console.log('获取到的staffId:', staffId)
  if (staffId) {
    isEdit.value = true
    formTitle.value = '编辑服务人员'
    fetchStaffDetails(Number(staffId))
  }
})

const fetchStaffDetails = async (id: number) => {
  try {
    console.log('获取服务人员详情，ID:', id)
    const response = await staffsApi.getById(id)
    console.log('服务人员详情返回', response)
    if (response.code === 200 && response.data) {
      // 直接使用后端返回数据
      Object.assign(form, response.data)
      console.log('表单数据已更新:', form)
    } else {
      ElMessage.error(response.msg || '获取服务人员详情失败')
    }
  } catch (error) {
    console.error('获取服务人员详情失败:', error)
    ElMessage.error('获取服务人员详情失败')
  }
}

const handleSubmit = () => {
  console.log('开始提交表单，当前状态:', isEdit.value ? '编辑' : '新增')
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        console.log('表单验证通过，准备提交数据:', form)
        let response
        if (isEdit.value) {
          console.log('调用更新API')
          response = await staffsApi.update(form)
        } else {
          console.log('调用新增API')
          response = await staffsApi.add(form)
        }
        console.log('API响应结果:', response)
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '服务人员更新成功' : '服务人员创建成功')
          router.push('/system/staffs')
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

const handleReset = () => {
  formRef.value?.resetFields()
}

const goBack = () => {
  router.push('/system/staffs')
}
</script>

<style scoped>
.form-container-wrap {
  padding: 20px;
}
.form-card {
  max-width: 600px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-content {
  padding-top: 20px;
}
</style> 